package com.tianshi.yingxue.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tianshi.yingxue.dao.CategoryMapper;
import com.tianshi.yingxue.dto.TwoPageParam;
import com.tianshi.yingxue.entity.Category;
import com.tianshi.yingxue.exception.BusinessException;
import com.tianshi.yingxue.page.PageParam;
import com.tianshi.yingxue.page.PageResult;
import com.tianshi.yingxue.page.Result;
import com.tianshi.yingxue.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public PageResult<Category> queryOnePage(PageParam pageParam) {
        // 1. 开启分页
        PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());

        // 2. 构造查询条件：级别=1
        Example example = new Example(Category.class);
        example.createCriteria().andEqualTo("levels", 1);

        // 3. 执行查询并封装分页结果
        List<Category> categoryList = categoryMapper.selectByExample(example);
        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);

        return new PageResult<>(pageInfo);
    }
    @Override
    public PageResult<Category> queryTwoPage(TwoPageParam twoPageParam) {
        // 1. 分页设置
        PageHelper.startPage(twoPageParam.getPage(), twoPageParam.getPageSize());

        // 2. 条件构造：二级类别(levels=2) + 父级ID匹配
        Example example = new Example(Category.class);
        example.createCriteria()
                .andEqualTo("levels", 2)
                .andEqualTo("parentId", twoPageParam.getCategoryId());

        // 3. 查询封装
        List<Category> categoryList = categoryMapper.selectByExample(example);
        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
        return new PageResult<>(pageInfo);
    }
    @Override
    public Category queryById(Integer id) {
        // 调用通用Mapper按主键查询
        Category category = categoryMapper.selectByPrimaryKey(id);
        // 数据不存在时的异常处理
        if (category == null) {
            throw new BusinessException("类别不存在，ID：" + id);
        }
        return category;
    }
    @Override
    public List<Category> queryByLevels(Integer levels) {
        // 1. 构造查询条件：级别=传入值
        Example example = new Example(Category.class);
        example.createCriteria().andEqualTo("levels", levels);

        // 2. 执行查询并返回列表
        return categoryMapper.selectByExample(example);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> add(Category category) {
        // 1. 校验类别名称（前端已校验，后端二次校验）
        if (category.getCateName() == null || category.getCateName().length() < 3 || category.getCateName().length() > 20) {
            throw new BusinessException("类别名称长度必须在3-20个字符之间");
        }

        // 2. 自动判断类别级别并校验唯一性
        Integer parentId = category.getParentId();
        if (parentId == null || parentId == 0) {
            // 一级类别：levels=1，parentId设为null
            category.setLevels(1);
            category.setParentId(null);

            // 关键：检查一级分类是否已存在同名类别
            Example example = new Example(Category.class);
            example.createCriteria()
                    .andEqualTo("levels", 1)  // 只查一级分类
                    .andEqualTo("cateName", category.getCateName());  // 名称相同
            long count = categoryMapper.selectCountByExample(example);
            if (count > 0) {
                return Result.fail("一级类别名称已存在，请更换名称");
            }
        } else {
            // 二级类别：校验父类别是否为一级
            Category parentCategory = categoryMapper.selectByPrimaryKey(parentId);
            if (parentCategory == null || parentCategory.getLevels() != 1) {
                return Result.fail("父类别不存在或不是一级类别，父ID: " + parentId);
            }
            category.setLevels(2);
        }

        // 3. 执行添加
        int count = categoryMapper.insertSelective(category);
        if (count != 1) {
            return Result.fail("添加类别失败");
        }

        log.info("添加类别成功: {}", category);
        return Result.success("添加成功");
    }
    /**
     * 修改类别（仅更新名称）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Category category) {
        System.out.println("接收到的所有数据: " + category);
        // 1. 检验必要参数
        if (category.getId() == null) {
            throw new BusinessException("类别ID不能为空");
        }
        if (category.getCateName() == null || category.getCateName().length() < 3 || category.getCateName().length() > 20) {
            throw new BusinessException("类别名称长度必须在3-20个字符之间");
        }

        // 2. 检验类别是否存在
        Category oldCategory = categoryMapper.selectByPrimaryKey(category.getId());
        if (oldCategory == null) {
            throw new BusinessException("类别不存在，ID：" + category.getId());
        }

        // 3. 只更新名称（避免修改级别、父ID等关键字段）
        Category updateCategory = new Category();
        updateCategory.setId(category.getId());
        updateCategory.setCateName(category.getCateName());

        // 4. 执行修改
        int count = categoryMapper.updateByPrimaryKeySelective(updateCategory);
        if (count != 1) {
            throw new BusinessException("修改类别失败");
        }
        log.info("修改类别成功：ID={}, 新名称={}", category.getId(), category.getCateName());
    }
    /**
     * 删除类别（一级类别需先删子类别）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) {
        // 1. 校验类别是否存在
        Category category = categoryMapper.selectByPrimaryKey(id);
        if (category == null) {
            throw new BusinessException("类别不存在，ID：" + id);
        }

        // 2. 若为一级类别，先检查是否有二级子类别
        if (category.getLevels() == 1) {
            Example example = new Example(Category.class);
            example.createCriteria().andEqualTo("parentId", id); // 子类别parentId=当前一级ID
            long childCount = categoryMapper.selectCountByExample(example); // 统计子类别数量
            if (childCount > 0) {
                throw new BusinessException("该一级类别下有二级类别，无法删除");
            }
        }

        // 3. 执行删除
        int count = categoryMapper.deleteByPrimaryKey(id);
        if (count != 1) {
            throw new BusinessException("删除类别失败");
        }
        log.info("删除类别成功：ID={}", id);
    }

}
